package com.zhj.user.controller;


import com.zhj.common.util.CookieUtils;
import com.zhj.common.util.JsonUtils;
import com.zhj.user.entity.dto.UserDTO;
import com.zhj.user.entity.dto.UserRegisterDTO;
import com.zhj.user.entity.pojo.User;
import com.zhj.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;

@RequestMapping("/passport")
@RestController
@Api(tags = "用户登录相关接口")
@Validated
public class PassportController {

    @Resource
    private UserService userService;

    @GetMapping("usernameIsExist")
    @ApiOperation("判断用户是否存在根据用户名")
    public boolean usernameIsExist(@RequestParam("username") @NotEmpty(message = "账号不能为空") String username) {
        return userService.usernameIsExist(username);
    }

    @GetMapping("getUserInfo/{id}")
    @ApiOperation("查询用户信息")
    public User getUserInfo(@PathVariable("id") String id) {
        return userService.selectByPrimaryKey(id);
    }

    @PostMapping("/regist")
    @ApiOperation("注册账号信息")
    public boolean createUser(@RequestBody @Valid UserRegisterDTO userDTO,
                              HttpServletRequest request,
                              HttpServletResponse response) {
        User user = this.userService.createUser(userDTO);
        setNullProperty(user);
        //设置cookies
        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(user), true);
        return true;
    }

    @PostMapping("login")
    public User login(@RequestBody UserDTO userDTO,
                      HttpServletRequest request,
                      HttpServletResponse response) {
        User user = this.userService.login(userDTO);
        setNullProperty(user);

        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(user), true);
        return user;
    }

    @ApiOperation(value = "用户退出登录", notes = "用户退出登录", httpMethod = "POST")
    @PostMapping("logout")
    public void logout(@RequestParam String userId,
                       HttpServletRequest request,
                       HttpServletResponse response) {
        // 清除用户的相关信息的cookie
        CookieUtils.deleteCookie(request, response, "user");
    }

    /**
     * 将不需要的数据设置为空
     *
     * @param user
     */
    private void setNullProperty(User user) {
        user.setPassword(null);
        user.setMobile(null);
        user.setEmail(null);
        user.setCreatedTime(null);
        user.setUpdatedTime(null);
        user.setBirthday(null);
    }


}
